/*
 * iShopPlace Project.
 */
package ishopplace.view.bean;

import ishopplace.model.businessobject.Order;
import ishopplace.model.exception.iShopPlaceException;
import ishopplace.view.util.FacesUtils;

import javax.faces.FacesException;


/**
 * Order backing bean.
 * 
 * @author <a href="mailto:derek@derekshen.com">Derek Y. Shen</a>
 */
public class OrderBean extends BaseBean {
    private Order order;
    
    /**
     * Constructor.
     * <p>
     * Initialize order bean based on the account bean
     * and shopping cart bean.
     */
    public OrderBean() {
    	super();
        this.logger.debug("Creating order bean");
        this.order = new Order();
        AccountBean accountBean = (AccountBean)FacesUtils.getManagedBean(BeanNames.ACCOUNT_BEAN);
        CartBean cartBean = (CartBean)FacesUtils.getManagedBean(BeanNames.CART_BEAN);
        
        String msg = "";
        if (accountBean == null) {
            msg += "You need to signon first. ";
        }
        if (cartBean == null) {
            msg += "Shopping cart can not be found.";
        }
        
        if (!msg.equals("")) {
            throw new FacesException("Unable to checkout: " + msg);
        }
        
        this.order.init(accountBean.getAccount(), cartBean.getCart());
        this.logger.debug("Order bean is created");
    }
    
    /**
     * Backing bean action to create a new order.
     * 
     * @return the navigation result
     */
    public String createOrderAction() {
        this.logger.debug("createOrderAction is invoked");
        try {
            this.serviceLocator.getOrderService().saveOrder(this.order);
            //clear shopping cart in session
            FacesUtils.resetManagedBean(BeanNames.CART_BEAN);
            return NavigationResults.SUCCESS;
        } catch (iShopPlaceException me) {
            String msg = "Could not create your order: ";
            this.logger.error(msg, me);
            FacesUtils.addErrorMessage(msg + " Internal Error");
            return NavigationResults.FAILURE;
        }
    }
    
    public Order getOrder() {
        return this.order;
    }
}
